package com.linchaoen.elema.controller;

import com.linchaoen.elema.model.entity.User;
import com.linchaoen.elema.model.request.LoginRequest;
import com.linchaoen.elema.model.request.ResetPwdRequest;
import com.linchaoen.elema.service.UserService;
import com.linchaoen.elema.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/pri/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("register")
    public JsonData register(@RequestBody Map<String, String> userInfo) {

        int row = userService.register(userInfo);

        return row == 1 ? JsonData.buildSuccess("注册成功") : JsonData.buildError("注册失败");
    }

    @PostMapping("login")
    public JsonData login(@RequestBody LoginRequest loginRequest) {
        String token = userService.findByPhoneAndPwd(loginRequest.getPhone(), loginRequest.getPwd());
        return token == null ? JsonData.buildError("登陆失败") : JsonData.buildSuccess(token);
    }

    @GetMapping("get_user_info")
    public JsonData getUserInfo(HttpServletRequest request) {
        Integer id = (Integer) request.getAttribute("uid");
        String name = (String) request.getAttribute("name");
        if (id == null) {
            return JsonData.buildError("查询失败");
        }
        User user = userService.findUserById(id);
        return JsonData.buildSuccess(user);

    }

    @GetMapping("update_user_info")
    public JsonData updateUserInfo(HttpServletRequest request,
                                   @RequestParam(value = "name") String name,
                                   @RequestParam(value = "signature") String signature) {
        Integer uid = (Integer) request.getAttribute("uid");
        int rows = userService.updateUserInfo(uid, name, signature);
        return rows == 1 ? JsonData.buildSuccess() : JsonData.buildError("修改失败");
    }

    @PostMapping("reset_pwd")
    public JsonData resetPwd(HttpServletRequest request, @RequestBody ResetPwdRequest resetPwdRequest) {
        Integer uid = (Integer) request.getAttribute("uid");
        int rows = userService.resetPwd(uid, resetPwdRequest.getOldPwd(), resetPwdRequest.getNewPwd());
        return rows == 1 ? JsonData.buildSuccess() : JsonData.buildError("修改失败");
    }



}
